<template>
  <Layout>
    <Breadcrumb>
      <BreadcrumbItem>文件管理</BreadcrumbItem>
      <BreadcrumbItem>文件分类</BreadcrumbItem>
    </Breadcrumb>
    <Content>

      <Row :style="{margin:'10px 0'}" :gutter="15">
        <i-col span="8" style="margin-left: 0">
          <Card :bordered="false">
            <Tree :data="data_tree" :load-data="loadData" :render="renderContent"></Tree>
          </Card>
        </i-col>
        <i-col  span="16" style="position: fixed;right: 30px ;    width: calc(66.66666667% - 40px);">
          <Card :bordered="false">
            <div slot="title">{{parent_menu}}</div>
            <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="70">
              <FormItem label="分类名称" prop="title">
                <Input v-model.trim="formItem.title" placeholder="输入分类名称"></Input>
              </FormItem>
              <FormItem label="上传图标">
                <Upload
                  type="drag"
                  :format="['jpg','jpeg','png']"
                  :max-size="2048"
                  :show-upload-list="false"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :before-upload="handleBeforeUpload"
                  name="up_file"
                  style="width: 300px;float: left"
                  :action="CD_.qj_url + 'index/Fileup/setfileimg'">
                  <div style="padding: 20px 0">
                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                    <p>220*124  限制格式jpg、jpeg、png，大小不能超过2M</p>
                  </div>
                </Upload>
                <Tooltip content="点击图片可以删除本图标" placement="right">
                  <img :src="CD_.qj_url + formItem.img_src" alt="" style="float: left;width: 220px;height:124px;margin: 0 15px" @click="remove_img">
                </Tooltip>

              </FormItem>
              <FormItem label="备注" prop="description">
                <Input v-model.trim="formItem.description" type="textarea" :rows="2" placeholder="备注" />
              </FormItem>
              <FormItem label="启用状态" >
                <RadioGroup v-model="formItem.state">
                  <Radio label="Enable">
                    <span>启用</span>
                  </Radio>
                  <Radio label="Disable">
                    <span>禁用</span>
                  </Radio>
                </RadioGroup>
              </FormItem>
              <FormItem>
                <Button type="primary" :loading="isLoading" @click="add_data('formItem')">确认提交</Button>
              </FormItem>
            </Form>

            <Spin fix  v-if="spinShow">请先在右边选择对应操作</Spin>
          </Card>

        </i-col>
      </Row>

    </Content>



    <!--删除提示-->
    <Modal v-model="remove_modal" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>删除确认</span>
      </p>
      <div style="text-align:center">
        <p>您即将删除这选中的角色，该角色下的用户都将数去角色对应的权限。确认删除吗?</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long  :loading="modal_loading"  @click="">删除</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
  export default {
    name: 'Role',
    data() {
      const validateData = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('Age cannot be empty'));
        }
        // 请求后天查询该分类有没有
        this.$http({
          method: 'post',
          url: this.CD_.qj_url + 'index/Treeclass/validateData',
          data: {
            value: value,
            parent_id: this.active_data.id,
          }
        }).then(function (res) {
          var json = res.data;
          if (json.status == 1) {
            return callback();
          } else {
            return callback(new Error('该分类名称已存在'));
          }

        }.bind(this)).catch(function (err) {
          return callback(new Error('输入内容校验失败'));
        }.bind(this))
      };
      return {
        treeID: 0,
        spinShow: true,
        remove_modal:false ,
        index_modal:1 , //来区别 添加1  修改2
        active_data:[] ,//选中的当前节点
        parent_menu:'已选菜单' ,
        isLoading: false,//提交数据时按钮的loading效果
        uploadList: [],//上传队列
        modal_loading: false,//删除loading
        formItem: {
          id: '',
          title: '',
          description: '',
          img_src: '',
          state: 'Enable'
        },
        ruleValidate: {
          title: [
            {required: true, message: '请输入分类名称', trigger: 'blur'},
            {validator: validateData, trigger: 'blur'}
          ]
        },
        data_tree: [
          {
            id: 0 ,
            title: '文件分类',
            expand: true,
            render: (h, { root, node, data }) => {
              return h('span', {
                style: {
                  display: 'inline-block',
                  width: '100%'
                }
              }, [
                h('span', [
                  h('Icon', {
                    props: {
                      type: 'ios-folder-outline'
                    },
                    style: {
                      marginRight: '8px'
                    }
                  }),
                  h('span', data.title)
                ]),
                h('span', {
                  style: {
                    display: 'inline-block',
                    float: 'right',
                    marginRight: '32px'
                  }
                }, [
                  h('Button', {
                    props: Object.assign({}, this.buttonProps, {
                      icon: 'ios-add',
                      type: 'primary'
                    }),
                    style: {
                      width: '99px',
                      display:this.CD_.btn_List.add_btn?"inline-block":"none",
                    },
                    on: {
                      click: () => { this.append(data) }
                    }
                  })
                ])
              ]);
            },
            children: [
              {
                id: 1,
                title: '案例一级分类',
                expand: true,
                children: [
                  {
                    id: 2,
                    title: '案例二级分类_1',
                    expand: true
                  },
                  {
                    id: 3,
                    title: '案例二级分类_2',
                    expand: true
                  }
                ]
              }
            ]
          }
        ],
        buttonProps: {
          type: 'default',
          size: 'small',
        }
      }
    },
    methods: {
      loadData (item, callback) {
        // 异步加载
        this.$http({
          method: 'get',
          url: this.CD_.qj_url + 'index/Treeclass/csh_fl?id='+ item.id,
        }).then(function (res) {
          var json = res.data
          if (json.status) {
            callback(json.data_list);
          } else {
            callback();
          }
          this.isLoading = false;
        }.bind(this)).catch(function (err) {
          this.$Notice.error({title: '分类查询，错误：',desc:'错误：'+ err});
          this.isLoading = false;
        }.bind(this))

      },
      handleFormatError (file) {
        //文件格式错误提示
        this.$Notice.warning({
          title: '文件格式不正确',
          desc:  file.name + '的文件格式不正确, 请选择jpg、jpeg、png其中一种。'
        });
      },
      handleMaxSize (file) {
        this.$Notice.warning({
          title: '文件大小超出限制',
          desc: file.name + '文件过大, 不能超过2M。'
        });
      },
      handleSuccess (res, file) {//上传成功
        this.uploadList.push({
          'name': file.name,
          'url': res.file_src,
          'class': res.file_class
        }) ;

        this.formItem.img_src = res.file_src ;
      },
      handleBeforeUpload () {
        const check = this.uploadList.length < 1;
        if (!check) {
          this.$Notice.warning({
            title: '只能上传一个分类图标。'
          });
        }
        return check;
      },
      handleRemove (file) {
//        删除文件
        console.log(file);
        const fileList = this.uploadList;
        this.uploadList.splice(fileList.indexOf(file), 1);
        //删除文件
        this.formItem.img_src = '' ;//重置图片

        if(file.response.file_src != undefined){
          this.$http({
            method: 'post',
            url: this.CD_.qj_url + 'index/Fileup/remove_file',
            data: {
              url: file.response.file_src,
            }
          }).then(function (res) {
            var json = res.data
            if (json.status) {
              this.$Notice.success({title: '成功删除已选文件，可重新选择~~~'});
            } else {
              this.$Notice.error({title: '删除失败~~'});
            }
            this.isLoading = false;
          }.bind(this)).catch(function (err) {
            this.$Notice.error({title: '文件删除，错误：',desc:'错误：'+ err});
            this.isLoading = false;
          }.bind(this))
        }

      },
      renderContent (h, { root, node, data }) {
        return h('span', {
          style: {
            display: 'inline-block',
            width: '100%'
          }
        }, [
          h('span', [
            h('Icon', {
              props: {
                type: 'ios-paper-outline'
              },
              style: {
                marginRight: '8px'
              }
            }),
            h('span', data.title)
          ]),
          h('span', {
            style: {
              display: 'inline-block',
              float: 'right',
              marginRight: '32px'
            }
          }, [
            h('Button', {
              props: Object.assign({}, this.buttonProps, {
                icon: 'ios-add'
              }),
              style: {
                marginRight: '8px',
                display:this.CD_.btn_List.add_btn?"inline-block":"none",
              },
              on: {
                click: () => { this.append(data) }
              }
            }),
            h('Button', {
              props: Object.assign({}, this.buttonProps, {
                icon: 'ios-remove'
              }),
              style: {
                marginRight: '8px',
                display:this.CD_.btn_List.remove_btn?"inline-block":"none",
              },
              on: {
                click: () => { this.remove(root, node, data) }
              }
            }),
            h('Button', {
              props: Object.assign({}, this.buttonProps, {
                icon: 'ios-create-outline'
              }),
              style: {
                display:this.CD_.btn_List.edit_btn?"inline-block":"none",
              },
              on: {
                click: () => { this.edit(root, node, data) }
              }
            })
          ])
        ]);
      },
      append (data) { //添加
        this.spinShow = false ;
        this.active_data = data ;
        this.index_modal = 1 ;
        this.formItem = {
          id: '',
          title: '',
          description: '',
          img_src: '',
          state: 'Enable'
        }; //重置菜单

        if(this.active_data.title == '文件分类'){
          this.parent_menu = '添加顶级分类'
        }else {
          this.parent_menu = '添加【'+this.active_data.title+'】的下级分类' ;
        }
      },
      remove (root, node, data) { //删除
        /*======================================================
        *@author wf_Huang
        *@Time 2018/10/23 8:58
        *=======================================================
        *@function  删除分类
        *=====================================================*/
        this.$Modal.confirm({
          title: '删除确认',
          content: '<p>删除分类后，对应的下级分类也会一起删除。但不影响该分类下的文件，你确定要删除分类吗？</p>',
          loading: true,
          onOk: () => {
            this.$http({
              method: 'post',
              url: this.CD_.qj_url + 'index/Treeclass/remove_data',
              data: {
                id: data.id,
              }
            }).then(function (res) {
              var json = res.data
              if (json.status) {
                this.$Notice.success({title: '成功删除分类~~~'});
                const parentKey = root.find(el => el === node).parent;
                const parent = root.find(el => el.nodeKey === parentKey).node;
                const index = parent.children.indexOf(data);
                parent.children.splice(index, 1);
                this.$Modal.remove();
              } else {
                this.$Notice.error({title: '分类删除失败~~'});
              }
              this.isLoading = false;
            }.bind(this)).catch(function (err) {
              this.$Notice.error({title: '分类删除，错误：',desc:'错误：'+ err});
              this.isLoading = false;
            }.bind(this))
          }
        });
      },
      edit (root, node, data) { //修改

        this.spinShow = false ;
        this.active_data = data ;
        this.index_modal = 2 ;
        this.parent_menu = '编辑【'+this.active_data.title+'】分类信息' ;
        console.log(data) ;
        this.formItem = data ;

        this.uploadList.splice(0, 1);

      },
      remove_img(){
        /*======================================================
        *@author wf_Huang
        *@Time 2019/2/18 16:59
        *=======================================================
        *@function  删除 图标
        *=====================================================*/
        this.formItem.img_src = '' ;
      },
      edit_data(){
        this.$http({
          method: 'post',
          url: this.CD_.qj_url + 'index/Treeclass/edit_data',
          data: {
            title: this.formItem.title,
            description: this.formItem.description,
            state: this.formItem.state,
            img_src: this.formItem.img_src,
            id: this.formItem.id
          }
        }).then(function (res) {
          var json = res.data
          if (json.status) {
            this.$Notice.success({title: '成功编辑分类~~~'});

            this.active_data.title = this.formItem.title ;
          } else {
            this.$Notice.error({title: '未改变该分类信息~~'});
          }
          this.isLoading = false;
        }.bind(this)).catch(function (err) {
          this.$Notice.error({title: '分类编辑，错误：',desc:'错误：'+ err});
          this.isLoading = false;
        }.bind(this))
      },
      add_data(data) {
        /*======================================================
        *@author wf_Huang
        *@Time 2018/6/12 11:55
        *=======================================================
        *@function  添加分类
        *=====================================================*/
        if(this.index_modal == 1){
          this.$refs[data].validate((valid) => {
            if (valid) {
              this.$http({
                method: 'post',
                url: this.CD_.qj_url + 'index/Treeclass/addTree',
                data: {
                  title: this.formItem.title,
                  description: this.formItem.description,
                  state: this.formItem.state,
                  img_src: this.formItem.img_src,
                  parent_id: this.active_data.id
                }
              }).then(function (res) {
                var json = res.data
                if (json.status) {
                  this.$Notice.success({title: '成功添加分类~~~'});

                  //赋值个TREE
                  const children = this.active_data.children || [];
                  children.push(json.data);
                  this.$set(this.active_data, 'children', children);

//                  this.getTree_data();
                  this.spinShow = true ;
                } else {
                  this.$Notice.error({title: '添加分类失败~~~'});
                }
                this.isLoading = false;
              }.bind(this)).catch(function (err) {
                this.$Notice.error({title: '添加分类失败，错误：',desc:'错误：'+ err});
                this.isLoading = false;
              }.bind(this))
            } else {
              this.$Notice.error({title: '分类信息填写有误'});
              this.isLoading = false;
            }
          })
        }else {
          this.edit_data() ;
        }

      },
      getTree_data() {
        /*======================================================
        *@author wf_Huang
        *@Time 2018/10/22 21:35
        *=======================================================
        *@function  获取初始化分类
        *=====================================================*/
        this.$http({
          method: 'get',
          url: this.CD_.qj_url + 'index/Treeclass/csh_fl?id='+ this.treeID,
        }).then(function (res) {
          var json = res.data
          if (json.status) {
            this.data_tree[0].children = json.data_list ;
          } else {
            this.$Notice.error({title: '分类查询，错误：'+res.msg});
          }
          this.isLoading = false;
        }.bind(this)).catch(function (err) {
          this.$Notice.error({title: '分类查询，错误：',desc:'错误：'+ err});
          this.isLoading = false;
        }.bind(this))
      }

    },
    mounted() {
      this.getTree_data();
    }
  }
</script>

<style scoped>
  .user_text{
    font-size: 16px;
    color: rgba(0, 0, 0, 0.85098);
    line-height: 18px;
    display: block;
    margin-bottom: 16px;
  }
  .ivu-col{
    font-size: 14px;
    line-height: 35px;
  }
</style>
